﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace Web.group
{
    public partial class employee : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SetDivePage(ref GridView1, ref GV);
            if (!IsPostBack)
            {
                Hashtable user = PhoneBook.Users.Users.get(Commons.StrUtil.FormatValue(Session["userid"]));
                DataSet ds = PhoneBook.Group.Department.list(Commons.StrUtil.FormatValue(user["groupid"]));
                Commons.ControlUtil.BindDDL(ddl_department, ds, "departmentname", "departmentid", "请选择部门", "");


                if (user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(user["IsBOOper"]))
                {
                    Hashtable bo = new Hashtable();
                    bo = PhoneBook.Group.BranchOffice.get(Commons.StrUtil.FormatValue(user["bo"]));
                    //ddlBo.DataSource = bo;
                    //ddlBo.DataTextField = "boname";
                    //ddlBo.DataValueField = "id";
                    //ddlBo.DataBind();
                    ddlBo.Items.Add(new ListItem(Commons.StrUtil.FormatValue(bo["boname"]), Commons.StrUtil.FormatValue(bo["id"])));
                }
                else
                {
                    ds = PhoneBook.Group.BranchOffice.list(Commons.StrUtil.FormatValue(user["groupid"]));
                    Commons.ControlUtil.BindDDL(ddlBo, ds, "boname", "id", "非分公司", "");
                    ddlBo.Items.Insert(0, new ListItem("全部", "-1"));
                }

                QueryData();

                ShowTipMsg(Commons.StrUtil.FormatValue(user["groupid"]));
            }
        }

        private void ShowTipMsg(string strGroupId)
        {
            //Hashtable user = PhoneBook.Users.Users.get(Commons.StrUtil.FormatValue(Session["userid"]));

            Hashtable ht = PhoneBook.Group.Employee.getpercent(strGroupId);

            string strTipMsg = string.Empty;

            if (decimal.Parse(ht["empercent"].ToString()) < 0.8M)
            {
                strTipMsg = string.Format("您选择的服务可开通{0}个用户，已开通{1}个用户", ht["totalnum"], ht["emcount"]);
                Helper.ShowMessage(u_message, controls.UCMessageType.success, strTipMsg);
            }
            else
            {
                strTipMsg = string.Format("您选择的服务可开通{0}个用户，已开通{1}个用户,请您及时升级服务，以免耽误使用", ht["totalnum"], ht["emcount"]);
                Helper.ShowMessage(u_message, controls.UCMessageType.error, strTipMsg);
            }
        }

        public override void QueryData()
        {
            string departmentid = ddl_department.SelectedValue;

            Hashtable user = PhoneBook.Users.Users.get(Commons.StrUtil.FormatValue(Session["userid"]));

            DataSet ds = new DataSet();

            if (user["IsBOOper"] == DBNull.Value || !Convert.ToBoolean(user["IsBOOper"]))
            {
                if (ddlBo.SelectedValue == "-1")
                {
                    ds = PhoneBook.Group.Employee.query(Commons.StrUtil.FormatValue(user["groupid"]), departmentid);
                }
                else
                {
                    ds = PhoneBook.Group.Employee.query(Commons.StrUtil.FormatValue(user["groupid"]), departmentid, ddlBo.SelectedValue);
                }
            }
            else if (user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(user["IsBOOper"]))
            {
                ds = PhoneBook.Group.Employee.query(Commons.StrUtil.FormatValue(user["groupid"]), departmentid, Commons.StrUtil.FormatValue(user["bo"]));
            }

            //绑定数据集
            GVDataBind(ref GridView1, ref GV, ds);
        }

        public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string employeeid = e.CommandArgument.ToString();

            Hashtable employee = PhoneBook.Group.Employee.get(employeeid);
            switch (e.CommandName)
            {
                case "del":
                    //string employeeid = e.CommandArgument.ToString();

                    //Hashtable employee = PhoneBook.Group.Employee.get(employeeid);
                    AddLog("删除了人员：{0}", employee["employeename"]);

                    PhoneBook.Group.Employee.del(employeeid);
                    Helper.ShowMessage(u_message, controls.UCMessageType.success, "删除成功");
                    QueryData();
                    break;
                case "reset":
                    Hashtable users = PhoneBook.Users.Users.getbyemployee(employee["employeeid"].ToString());

                    AddLog("重置了人员({0})的密码", users["userid"]);

                    string strPwd = employee["mobile"] == null ? "0000" : employee["mobile"].ToString();
                    if (strPwd.Length < 4)
                    {
                        int iadd = 4 - strPwd.Length;

                        for (int i = 0; i < iadd; i++)
                        {
                            strPwd += "0";
                        }
                    }
                    else
                    {
                        strPwd = strPwd.Substring(strPwd.Length - 4, 4);
                    }

                    Dx.ZcEncrypt.Encrypt3DES encrypt = new Dx.ZcEncrypt.Encrypt3DES();
                    strPwd = encrypt.EncryptString(strPwd);
                    users["userpwd"] = strPwd;
                    PhoneBook.Users.Users.edit(users);
                    Helper.ShowMessage(u_message, controls.UCMessageType.success, "重置密码成功");
                    break;
                default:
                    break;
            }
        }

        protected void btn_query_Click(object sender, EventArgs e)
        {
            QueryData();
        }

        protected void btn_export_Click(object sender, EventArgs e)
        {
            string filename = string.Format("employee{0}", Commons.StringUtil.GetID_15());
            Commons.FileUtil.GridExportExcel(GridView1, filename);
        }

        protected void btn_import_Click(object sender, EventArgs e)
        {
            HSSFWorkbook hssfworkbook;

            hssfworkbook = new HSSFWorkbook(fl_upload.FileContent);

            importemployee(hssfworkbook);
        }

        private void importemployee(HSSFWorkbook hssfworkbook)
        {
            Hashtable user = PhoneBook.Users.Users.get(Commons.StrUtil.FormatValue(Session["userid"]));

            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            //跳过首行
            rows.MoveNext();
            while (rows.MoveNext())
            {
                IRow row = (HSSFRow)rows.Current;

                if (row.LastCellNum <= 10) continue;

                Hashtable employee = new Hashtable();
                employee["employeename"] = Commons.StrUtil.FormatValue(row.GetCell(0));
                employee["age"] = Commons.StrUtil.FormatValue(row.GetCell(1));

                //插入部门
                Hashtable department = new Hashtable();
                department["departmentname"] = Commons.StrUtil.FormatValue(row.GetCell(2));
                department["groupid"] = user["groupid"];
                PhoneBook.Group.Department.add(department);
                string departmentid = PhoneBook.Group.Department.getmaxid();
                if (string.IsNullOrEmpty(departmentid))
                    continue;

                employee["departmentid"] = departmentid;
                employee["mobile"] = Commons.StrUtil.FormatValue(row.GetCell(3));
                employee["phone"] = Commons.StrUtil.FormatValue(row.GetCell(4));
                employee["email"] = Commons.StrUtil.FormatValue(row.GetCell(5));
                employee["shortnum"] = Commons.StrUtil.FormatValue(row.GetCell(6));

                employee["qq"] = Commons.StrUtil.FormatValue(row.GetCell(7));
                employee["msn"] = Commons.StrUtil.FormatValue(row.GetCell(8));
                employee["fax"] = Commons.StrUtil.FormatValue(row.GetCell(9));
                employee["duty"] = Commons.StrUtil.FormatValue(row.GetCell(10));

                //新增第11行为分公司，根据分公司名称查找对应的分公司编码，如果为null则跳过
                String strBoName = Commons.StrUtil.FormatValue(row.GetCell(11));

                int? boid = PhoneBook.Group.BranchOffice.GetIdByName(strBoName);

                if (boid == null) continue;

                employee["boid"] = boid;

                PhoneBook.Group.Employee.add(employee);
            }
            Helper.ShowMessage(u_message, controls.UCMessageType.success, "导入成功");
        }

        protected void btn_adduser_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox cb_sel = row.FindControl("cb_sel") as CheckBox;
                if (cb_sel == null) continue;
                if (GridView1.DataKeys.Count > 0)
                {
                    string employeeid = GridView1.DataKeys[row.RowIndex]["employeeid"].ToString();
                    string departmentid = GridView1.DataKeys[row.RowIndex]["departmentid"].ToString();
                    string groupid = GridView1.DataKeys[row.RowIndex]["groupid"].ToString();
                    string userid = GridView1.DataKeys[row.RowIndex]["userid"].ToString();
                    string employeename = GridView1.DataKeys[row.RowIndex]["employeename"].ToString();
                    string mobile = GridView1.DataKeys[row.RowIndex]["mobile"].ToString();
                    if (cb_sel.Checked)
                    {
                        if (string.IsNullOrEmpty(userid))
                        {
                            Hashtable newuser = new Hashtable();
                            newuser["username"] = mobile;
                            Dx.ZcEncrypt.Encrypt3DES encrypt = new Dx.ZcEncrypt.Encrypt3DES();
                            if (!string.IsNullOrEmpty(mobile) && mobile.Length > 3)
                                newuser["userpwd"] = mobile.Substring(mobile.Length - 4);//encrypt.EncryptString(Dx.ZcEncrypt.Encrypt.GetMD5(mobile.Substring(mobile.Length - 4)));
                            else
                                newuser["userpwd"] = "123456";//encrypt.EncryptString(Dx.ZcEncrypt.Encrypt.GetMD5("123456"));
                            newuser["nickname"] = employeename;
                            newuser["groupid"] = groupid;
                            newuser["employeeid"] = employeeid;
                            PhoneBook.Users.Users.addwebuser(newuser);
                            Hashtable role = PhoneBook.Manage.SysRole.getWebUserRole();
                            if (role != null)
                                PhoneBook.Manage.SysUserRole.add(newuser["userid"].ToString(), role["roleid"].ToString());
                        }
                    }
                    else
                    {
                        PhoneBook.Users.Users.del(userid);
                    }
                }
            }
            Helper.ShowMessage(u_message, controls.UCMessageType.success, "开通成功");
            QueryData();
        }

        protected string GetBoName(string boid)
        {
            if (string.IsNullOrEmpty(boid))
            {
                return string.Empty;
            }

            Hashtable bo = PhoneBook.Group.BranchOffice.get(boid);

            if (bo == null || bo.Count == 0)
            {
                return string.Empty;
            }

            return bo["boname"].ToString();
        }
    }
}